/* eslint-disable @typescript-eslint/no-explicit-any */
import { Nodes, dom } from '@knno/dom';
import { JSXProps, jsxGen } from '@knno/dom/jsx';
import { DATA } from '../symbol';

interface MutableProp extends JSXProps<Mutable> {
	host?: Nodes;
	render: (data?: any) => Nodes | Promise<Nodes>;
	data?: any;
}

export class Mutable extends Nodes {
	[DATA]: {
		render: (data: any) => Nodes | Promise<Nodes>;
	};
	constructor(attrs: MutableProp) {
		const hostNode = attrs.host ?? dom.div();
		const result = attrs.render(attrs.data);
		if (result instanceof Promise) {
			super(hostNode);
			result
				.then((value) => this.append(value))
				.catch((reason) => {
					console.error(reason);
				});
		} else {
			super(hostNode.append(result));
		}
		jsxGen(this, attrs, []);
		this[DATA] = {
			render: attrs.render,
		};
	}

	refresh(data?: any) {
		const result = this[DATA].render(data);
		if (result instanceof Promise) {
			result
				.then((value) => {
					this.html('').append(value);
					// this.emit(new Event('change'));
				})
				.catch((reason) => {
					console.error(reason);
				});
		} else {
			this.html('').append(result);
			// this.emit(new Event('change'));
		}
		return this;
	}
}
